import { verify } from "argon2";
import { add, endOf } from "ph-utils/date";
import { manager } from "typeorm-connection";
import { User, UserToken } from "../entities/index.js";
import { generateToken } from "../utils/utils.js";

export async function login(username: string, password: string) {
	const entityManager = manager();
	const user = await entityManager.findOneBy(User, { username });
	if (user == null) {
		return { code: 10001 };
	}
	const very = await verify(user.password, password);
	if (!very) {
		return { code: 10002 };
	}
	const token = generateToken(user.username);
	await entityManager.insert(UserToken, {
		token,
		expireTime: endOf(add(new Date(), 2, "date"), "unit"),
		status: 1,
		userId: user.id,
	});
	return { code: 200, token };
}
